﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SJ.Platform.Common;
using SJ.Platform.EFCore.DBOperation.DBOperation.MySQL.Sys;
using SJ.Platform.EFCore.Model;
using SJ.Platform.EFCore.Model.AuthorityManager;
using SJ.Platform.Extend.IOC.CurrentUser;
using SJ.Platform.Extend.ModelExtend;
using SJ.Platform.Extend.ModelExtend.SysAuthorityExt;
using SJ.Platform.Extend.Request;
using SJ.Platform.Extend.Response;

namespace SJ.Platform.Api.Controllers.AuthorityManager
{
    /// <summary>
    /// 权限操作接口
    /// </summary>
    [Route(GlobalVariableHandle.Scope_Api + "/Authority")]
    [ApiController]
    [Authorize(GlobalVariableHandle.Scope_Api)]
    public class AuthorityManagerController : ControllerBase
    {
        private readonly Sys_AuthorityHandle sys_AuthorityHandle;
        private readonly ICurrentUser _currentUser;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dbContext">数据库</param>
        /// <param name="currentUser">当前用户</param>
        public AuthorityManagerController(SJDBContext dbContext, ICurrentUser currentUser)
        {
            sys_AuthorityHandle = new Sys_AuthorityHandle(dbContext);
            _currentUser = currentUser;
        }

        /// <summary>
        /// 新增权限
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost("CreateAuthorityAsync")]
        public async Task<IActionResult> CreateAuthorityAsync([FromBody] SysAuthority model)
        {
            var Authority = new SysAuthority
            {
                Id = Guid.NewGuid().ToString(),
                AuthorityName = model.AuthorityName,
                Pid = model.Pid,
                AuthorityType = model.AuthorityType,
                MenuId = model.MenuId,
                AddTime = DateTime.Now,
                AddUserId = _currentUser.UserId,
                EditTime = DateTime.Now,
                EditUserId = _currentUser.UserId
            };
            try
            {
                bool result = await sys_AuthorityHandle.CreateAsync(Authority);
                return Ok(ApiNormalResponse<bool>.SetResponse(result ? ApiResponseStatus.Success : ApiResponseStatus.BadRequest, "权限添加" + (result ? "成功" : "失败"), result));
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiNormalResponse<bool>.SetResponse(ApiResponseStatus.BadRequest, "权限添加失败：" + ex.Message, false));
            }
        }

        /// <summary>
        /// 修改权限
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost("UpdateAuthorityAsync")]
        public async Task<IActionResult> UpdateAuthorityAsync([FromBody] SysAuthority model)
        {
            var Authority = new SysAuthority
            {
                Id = model.Id,
                AuthorityName = model.AuthorityName,
                Pid = model.Pid,
                AuthorityType = model.AuthorityType,
                MenuId = model.MenuId,
                AddTime = model.AddTime,
                AddUserId = model.AddUserId,
                EditTime = DateTime.Now,
                EditUserId = _currentUser.UserId
            };
            try
            {
                bool result = await sys_AuthorityHandle.UpdateAsync(Authority);
                return Ok(ApiNormalResponse<bool>.SetResponse(result ? ApiResponseStatus.Success : ApiResponseStatus.BadRequest, "权限修改" + (result ? "成功" : "失败"), result));
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiNormalResponse<bool>.SetResponse(ApiResponseStatus.BadRequest, "权限修改失败：" + ex.Message, false));
            }
        }

        /// <summary>
        /// 删除权限
        /// </summary>
        /// <param name="authorityId"></param>
        /// <returns></returns>
        [HttpGet("DeleteByAuthorityIdAsync/{authorityId}")]
        public async Task<IActionResult> DeleteByAuthorityIdAsync(string authorityId)
        {
            try
            {
                bool result = await sys_AuthorityHandle.DeleteByIdAsync(authorityId);
                return Ok(ApiNormalResponse<bool>.SetResponse(result ? ApiResponseStatus.Success : ApiResponseStatus.BadRequest, "删除权限" + (result ? "成功" : "失败"), result));
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiNormalResponse<bool>.SetResponse(ApiResponseStatus.BadRequest, "删除权限失败：" + ex.Message, false));
            }
        }

        /// <summary>
        /// 分页获取所有权限
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost("GetAllAuthoritiesAsync")]
        public async Task<IActionResult> GetAllAuthoritiesAsync([FromBody] ApiPageQueryRequest<SysAuthority> request)
        {
            try
            {
                var result = await sys_AuthorityHandle.GetAllAsync((int)request.PageIndex, (int)request.PageSize, ApiPageQueryRequest<SysAuthority>.GenerateCondition(request.Condition));
                return Ok(ApiPageQueryResponse<List<SysAuthorityExtend>>.SetResponse(ApiResponseStatus.Success, "查询成功", (int)request.PageIndex, (int)request.PageSize, result.count, result.authoriesExtList)); // 返回成功的响应
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiPageQueryResponse<List<SysAuthorityExtend>>.SetResponse(ApiResponseStatus.BadRequest, "查询失败：" + ex.Message, (int)request.PageIndex, (int)request.PageSize, 0, new List<SysAuthorityExtend> { }));
            }
        }

        /// <summary>
        /// 获取所有菜单权限
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetAllMenuAuthoritiesAsync")]
        public async Task<IActionResult> GetAllMenuAuthoritiesAsync()
        {
            try
            {
                var result = await sys_AuthorityHandle.GetAllAsync(authority => authority.AuthorityType == 1);
                return Ok(ApiNormalResponse<List<SysAuthority>>.SetResponse(ApiResponseStatus.Success, "查询成功",  result)); // 返回成功的响应
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiNormalResponse<List<SysAuthority>>.SetResponse(ApiResponseStatus.BadRequest, "查询失败：" + ex.Message, new List<SysAuthority> { }));
            }
        }

        /// <summary>
        /// 获取所有权限，并分层
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        [HttpGet("GetAllAuthoritiesToLevelAsync/{roleId}")]
        public async Task<IActionResult> GetAllAuthoritiesToLevelAsync(string roleId)
        {
            try
            {
                var result = await sys_AuthorityHandle.GetAllAuthoritiesToLevelAsync(roleId);
                return Ok(ApiNormalResponse<List<SysAuthorityExtend>>.SetResponse(ApiResponseStatus.Success, "查询成功", result)); // 返回成功的响应
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiNormalResponse<List<SysAuthorityExtend>>.SetResponse(ApiResponseStatus.BadRequest, "查询失败：" + ex.Message, new List<SysAuthorityExtend> { }));
            }
        }

        /// <summary>
        /// 给角色设置权限
        /// </summary>
        /// <param name="authorities"></param>
        /// <returns></returns>
        [HttpPost("SetAuthorityToRoleAsync")]
        public async Task<IActionResult> SetAuthorityToRoleAsync([FromBody] SysAuthorityConfigExtend authorities)
        {
            try
            {
                var result = await sys_AuthorityHandle.SetAuthorityToRoleAsync(authorities, _currentUser.UserId);
                return Ok(ApiNormalResponse<bool>.SetResponse(result ? ApiResponseStatus.Success : ApiResponseStatus.BadRequest, "配置权限" + (result ? "成功" : "失败"), result));
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiNormalResponse<bool>.SetResponse(ApiResponseStatus.BadRequest, "配置权限失败：" + ex.Message, false));
            }
        }
    }
}